﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GrapeCity.PAutoTester.Core;
using System.Threading;
using System.IO;

namespace GrapeCity.PAutoTesterConsole
{
    public class ConsoleTester
    {
        #region Fields

        ITestRunner _testRunner;

        #endregion Fields

        #region Properties

        public TestAssembly TestAssembly
        {
            get
            {
                return _testRunner.TestAssembly;
            }
        }

        public AssemblyType AssemblyType
        {
            get
            {
                if (this.TestAssembly == null)
                {
                    return AssemblyType.None;
                }
                return this.TestAssembly.AssemblyType;
            }
        }

        #endregion Properties

        #region Constructor

        public ConsoleTester(string assemblyPath)
        {
            if (assemblyPath == null)
            {
                throw new ArgumentNullException("Assembly path should not null.");
            }
            _testRunner = new TestRunner();
            _testRunner.Load(assemblyPath);
        }

        #endregion Constructor


        public void ExecuteTest(CommandLine commandLine)
        {
#if SILVERLIGHT
            if (AssemblyType == AssemblyType.Silverlight)
            {
                Config.Current.CurrentBrowser = GrapeCity.PAutoTester.Core.Silverlight.BrowserBrand.IE;
                if (Config.Current.TestBrowsers.Count > 0)
                    Config.Current.CurrentBrowser = Config.Current.TestBrowsers[0];
            }
#endif
            SimpleNameFilter filter = new SimpleNameFilter();
            filter.Add(TestAssembly.FullName);
            if (commandLine.HasCaseList())
            {
                // run case list.
                // add case list to the filter.
                string[] cases = commandLine.CaseList.Split(';');
                foreach (string caseName in cases)
                {
                    filter.Add(caseName);
                }            
            }
            else
            {
                // add all the cases to filter.
                foreach (var testClass in TestAssembly.TestClasses)
                {
                    filter.Add(testClass.FullName);
                    foreach (var method in testClass.TestMethods)
                    {
                        filter.Add(method.FullName);
                    }
                }
            }

            // run all.
            new Thread(new ThreadStart(delegate
            {
                _testRunner.Run(null, filter);
            })).Start();
        }
    }
}
